import { RsqlDataOperator } from '@/core/utils/rsql/types/RsqlDataOperator'
import RsqlBuilder from '@/core/utils/rsql/RsqlBuilder'
import { ApiObject } from 'amis-core/lib/types'
import { isEmpty, isNil } from 'lodash-es'
import lodash from 'lodash'

class RsqlUtils {
	addRsqlFilter = (api: ApiObject, context: any, filterName: string, operators: RsqlDataOperator[]): ApiObject => {
		if (isNil(context)) {
			return api
		}
		const newData = Object.assign({}, api.data)

		const builder: RsqlBuilder = RsqlBuilder.builder()
		operators.forEach(operator => {
			const paramPropertyName = operator.paramPropertyName ? operator.paramPropertyName : operator.propertyName
			const value = lodash.get(context, paramPropertyName)
			if (isNil(value)) {
				return
			}
			builder.add(operator.propertyName, value, operator.operator)
		})

		const queryString = builder.queryString()
		if (isEmpty(queryString)) {
			return api
		}
		newData[filterName] = queryString
		api.data = newData
		return api
	}
}

export default new RsqlUtils()
